$(function() {
  var htmlGet = decodeURI(location.search)
  var categoryId = getNum(htmlGet)
    // console.log(categoryid)
  function getNum(str) {
    // console.dir(/\d+/.exec(str));
    //exec()  返回一个数组，其中存放匹配的结果。如果未找到匹配，则返回值为 null
    if (!str || str.length == 0) {
      return "";
    } else {
      var ret = /\d+/.exec(str);
      if (!ret) {
        return "";
      }
      return parseInt(/\d+/.exec(str)[0]);
    }
  }
  $.ajax({
    url: "http://193.112.55.79:9090/api/getcategorybyid",
    type: "get",
    dataType: "json",
    data: { categoryid: categoryId },
    success: function(res) {
      // console.log(res)
      var product_name_str = template('product_name', res)
        // console.log(product_name_str)
      $('#all_classifiy').after(product_name_str)
    }
  })
  var nowPage = 1
  getList(nowPage)
  var pageTotal;
  // 分页渲染
  function getList(page) {
    $.ajax({
      url: "http://193.112.55.79:9090/api/getproductlist",
      type: "get",
      dataType: "json",
      data: {
        categoryid: categoryId,
        pageid: page
      },
      success: function(res) {
        // console.log(res)
        var productStr = template('productList', res)
        $('#product .product_list').html(productStr)
        pageTotal = Math.ceil(res.totalCount / res.pagesize)
          // var pageTotal = res.totalCount / res.pagesize
        // console.log(pageTotal)
        $('#dropdownMenu1').html(page + '/' + pageTotal + ' <span class="caret"></span>')
        var arr = []
          // 拼接字符串传入
        for (var i = 0; i < pageTotal; i++) {
          arr.push('<li><a href="#">第' + (i + 1) + '页</a></li>')
        }
        // console.log(arr)
        $(".dropdown-menu").html(arr.join(''));
      }
    })
  }

  // 页数

  $('#nextPage').on('click', function() {
    if (nowPage == pageTotal) {
      return;
    }
    nowPage++
    getList(nowPage)
      // console.log(123)
  })

  $('#prePage').on('click', function() {
      if (nowPage == 1) {
        return
      }
      nowPage--
      getList(nowPage)
        // console.log(123)
    })
    // 页数选择
  $('.dropdown-menu').on('click', 'li a', function(e) {
      // e.preventDefault()
      // console.log(this)
      nowPage = getNum($(this).text())
      getList(nowPage)
    })
    //返回首页
  $('.btn-back').on('click', function() {
      $(this).attr('href', '../index.html');
    })
    //返回顶部
  $('.footer_top .back').on('click', function() {
    var timeId = setInterval(function() {
      var target = 0;
      var leader = scroll().scrollTop;
      leader = leader + (target - leader) / 10;
      scrollTo(0, leader);
      if (leader == target) {
        clearInterval(timeId);
      }
    })
  })

  function scroll() {
    return {
      scrollTop: window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0,
      scrollLeft: window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft || 0,
    }
  }
})